<?php

// 缴纳保证金

namespace app\shop\controller;

use think\Db;
use think\Request;
use think\Session;
use think\Controller;
use app\shop\model\Member as MemberModel;
use app\shop\model\AuctionGoods as AuctionGoodsModel;
use app\shop\model\MemberAuction as MemberAuctionModel;

class Bond extends Controller
{

    /**
     * 缴纳保证金页面
     * @return mixed
     */
    public function index()
    {
        // 获取参数
        $auction_goods_id = Request::instance()->param('goods_id');

        // 用户信息
        $info = (new MemberModel)->where('id', Session::get('member_id'))->field('username,wechat_id,pay_pass')->find();

        // 保证金
        $bond = (new AuctionGoodsModel())->where('id', $auction_goods_id)->find();


        return $this->fetch('', [
            'mate_head' => '缴纳保证金',
            'info'      => $info,
            'bond'      => $bond,
        ]);

    }


    /**
     * 缴纳保证金
     * @return array
     */
    public function balance()
    {
        if (Request::instance()->isPost()) {
            // 获取保证金金额
            $price = Request::instance()->param('price');
            // 会员ID
            $member_id = Session::get('member_id');
            // 拍卖商品ID
            $goods_id = Request::instance()->param('goods_id');
            // 支付密码
            $pwd = Request::instance()->param('password');
            $pass = (new MemberModel())->where('id', Session::get('member_id'))->value('pay_pass');
            // 验证密码
            if (md5(md5($pwd)) != $pass) {
                return ['code' => 400, 'message' => '密码不正确'];
            }

            $find = (new AuctionGoodsModel())->where('id', $goods_id)->find();

            $blance_price = Db::name('member')->where('id', $member_id)->value('balance');

            if ($blance_price<$price) return ['code'=>404,'message'=> '余额不足'];

            Db::startTrans();
            try {

                // 会员拍卖纪录增加
                $ini = [
                    'auction_id'    => $find['auction_id'],
                    'goods_id'      => $goods_id,
                    'member_id'     => $member_id,
                    'reserve_price' => $price,
                    'status'        => 2
                ];

                (new MemberAuctionModel)->allowField(true)->save($ini);

                // 减少余额

                Db::name('member')->where('id', $member_id)->setDec('balance', $price);

                $con = [
                    'member_id'=>  $member_id,
                    'type_id'  => 1,
                    'price'    => $price,
                    'way'      => '充值',
                    'balance'  => $blance_price,
                    'status'   => 1,
                    'reason'   => '',
                    'order_number'  => self::createNumber(),
                    'create_time'  => time(),
                ];

                Db::name('member_withdraw')->insert($con);

                Db::commit();

                return ['code'=>200,'message'=> '支付成功'];
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ['code'=>404,'message'=> '支付失败'];
            }
        }
    }


    /**
     * 生成订单号
     */
    protected function createNumber()
    {
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $order_id;
    }
}